package simorg.actions;

import simorg.actions.enrollment.EnrollmentJob;
import simorg.controller.UserController;
import simorg.domain.Course;
import simorg.domain.persistence.CourseTable;
import simorg.view.ModelView;
import simorg.view.WebSessionContext;

public class UserBatchEnroll extends Action {

	public static String actionName = "batchenroll";
	public UserBatchEnroll() {
		super(actionName);
		this.controllerName = UserController.controllerName;
	}
	
	@Override
	public ModelView checkAccess(WebSessionContext wc) throws Exception {
		return this.checkAdminAccess(wc);
	}
	
	@Override
	public ModelView process(WebSessionContext wc) throws Exception {
		Course courseToEnroll = CourseTable.findById(wc.getDbConnection(), Integer.parseInt(wc.getRequestParameter("courseId")));
		if ( wc.hasReqeustParameter("batchEnroll") ) {
			String rawText = wc.getRequestParameter("batchEnroll");
			String [] lines = rawText.split("\n");
			for (String line : lines ) { 
				String [] fields = line.split(",");
				EnrollmentJob job = new EnrollmentJob(courseToEnroll, fields[1].trim(), fields[0].trim(), fields[2].trim());
				job.enroll(wc);
			}
		
		}
		Action redirect = new CourseView(String.valueOf(courseToEnroll.getId()));
		wc.redirectAdmin(redirect, "enrollment");
		return null;
	}

}
